import 'dart:async';

import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/barrage/barrage.dart';
import 'package:flutter_application_1/components/hide_scroll_shadow/hide_scroll_shadow.dart';
import 'package:flutter_application_1/components/hide_wave/hide_wave.dart';
import 'package:flutter_application_1/pages/test_page/prize_claw_index/tab_bar_1.dart';
import 'package:flutter_application_1/pages/test_page/prize_claw_index/tab_bar_2.dart';
import 'package:flutter_application_1/pages/test_page/prize_claw_index/tab_bar_3.dart';
import 'package:flutter_application_1/pages/test_page/prize_claw_index/tab_bar_4.dart';
import 'package:flutter_application_1/pages/test_page/prize_claw_index/tab_bar_5.dart';
import 'package:flutter_application_1/utils/source_utils.dart';

import 'components/barrage_one.dart';
import 'components/barrage_two.dart';

class PrizeClawIndex extends StatefulWidget {
  @override
  _PrizeClawIndexState createState() => _PrizeClawIndexState();
}

class _ThatTab {
  String label;
  Color bgColor;
  Color labelColor;
  Widget tabbar;

  _ThatTab({
    required this.label,
    required this.bgColor,
    required this.labelColor,
    required this.tabbar,
  });
}

class _PrizeClawIndexState extends State<PrizeClawIndex>
    with TickerProviderStateMixin {
  late TabController _tabController;

  late PageController _pageController;

  // 当前选择的 tab index
  ValueNotifier<int> _currentIndex = ValueNotifier<int>(0);

  // 滑动时 tab 没有动画，但是回调事件快
  // 用了判断是否点击跳转中，避免点击 tab 跳转时触发 PageView 的 onPageChanged
  bool _onTabing = false;

  void _onPageChanged(int page) {
    if (!_onTabing) {
      _tabController.animateTo(page);
      _currentIndex.value = page;
    }
  }

  void _onTabTap(int page) {
    if (_onTabing) return;
    _onTabing = true;
    _currentIndex.value = page;
    _pageController
        .animateToPage(
      page,
      duration: kTabScrollDuration,
      curve: Curves.ease,
    )
        .then((_) {
      _onTabing = false;
    });
  }

  // tab 列表
  List<_ThatTab> _tabList = [];

  // 循环计时器
  int _flag = 0;
  late Timer _timer;

  @override
  void initState() {
    super.initState();

    _pageController = PageController(
      initialPage: _currentIndex.value,
    );

    _tabList = [
      _ThatTab(
        label: '娃娃机',
        bgColor: Color.fromRGBO(255, 245, 150, 1),
        labelColor: Color.fromRGBO(5, 207, 162, 1),
        tabbar: TabBar1(
          bgColor: Color.fromRGBO(255, 245, 150, 1),
          primaryColor: Color.fromRGBO(5, 207, 162, 1),
        ),
      ),
      _ThatTab(
        label: '推币机',
        bgColor: Color.fromRGBO(254, 217, 128, 1),
        labelColor: Color.fromRGBO(180, 140, 19, 1),
        tabbar: TabBar2(
          bgColor: Color.fromRGBO(254, 217, 128, 1),
          primaryColor: Color.fromRGBO(180, 140, 19, 1),
        ),
      ),
      _ThatTab(
        label: '街机',
        bgColor: Color.fromRGBO(207, 243, 182, 1),
        labelColor: Color.fromRGBO(0, 186, 77, 1),
        tabbar: TabBar3(
          bgColor: Color.fromRGBO(207, 243, 182, 1),
          primaryColor: Color.fromRGBO(0, 186, 77, 1),
        ),
      ),
      _ThatTab(
        label: '扭蛋机',
        bgColor: Color.fromRGBO(193, 212, 255, 1),
        labelColor: Color.fromRGBO(130, 118, 244, 1),
        tabbar: TabBar4(
          bgColor: Color.fromRGBO(193, 212, 255, 1),
          primaryColor: Color.fromRGBO(130, 118, 244, 1),
          pageController: _pageController,
        ),
      ),
      _ThatTab(
        label: '口红机',
        bgColor: Color.fromRGBO(255, 236, 245, 1),
        labelColor: Color.fromRGBO(255, 105, 106, 1),
        tabbar: TabBar5(
          bgColor: Color.fromRGBO(255, 236, 245, 1),
          primaryColor: Color.fromRGBO(255, 105, 106, 1),
        ),
      ),
    ];

    _tabController = TabController(
      initialIndex: _currentIndex.value,
      length: _tabList.length,
      vsync: this,
    );

    _timer = Timer.periodic(Duration(seconds: 6), (timer) {
      Barrage.emit(
        context: context,
        child: _flag % 2 == 0
            ? BarrageOne(
                avatar:
                    'https://i2.hdslb.com/bfs/face/27956154ebc30ab1de758b6ad53daee844a2e42c.jpg@160w_160h_1c.jpg',
                name: 'fanzhiliang',
                operation: '推币推中了',
                result: '501奖励',
              )
            : BarrageTwo(
                avatar:
                    'https://i2.hdslb.com/bfs/face/27956154ebc30ab1de758b6ad53daee844a2e42c.jpg@160w_160h_1c.jpg',
                name: '蚊子腿细也是肉',
                operation: '抓到了',
                result: '可达鸭',
              ),
      );

      _flag++;
    });
  }

  @override
  void dispose() {
    _timer.cancel();

    Barrage.remove();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景
          ValueListenableBuilder(
            valueListenable: _currentIndex,
            builder: (BuildContext context, int currentIndex, Widget? child) {
              _ThatTab currentTab = _tabList[currentIndex];

              return Container(
                decoration: BoxDecoration(
                  color: currentTab.bgColor,
                ),
              );
            },
          ),
          // 页面内容
          SafeArea(
            top: true,
            child: Column(
              children: [
                IndexAppbar(),
                // TabBar
                Container(
                  height: 46,
                  alignment: Alignment.center,
                  child: HideWave(
                    child: TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      indicator: BoxDecoration(
                        color: Colors.transparent,
                      ),
                      indicatorWeight: 0,
                      indicatorColor: Colors.transparent,
                      labelPadding: EdgeInsets.zero,
                      onTap: _onTabTap,
                      tabs: List.generate(
                        _tabList.length,
                        (index) => ValueListenableBuilder(
                          valueListenable: _currentIndex,
                          builder: (
                            BuildContext context,
                            int currentIndex,
                            Widget? child,
                          ) {
                            _ThatTab tab = _tabList[index];
                            _ThatTab currentTab = _tabList[currentIndex];
                            return Container(
                              width: 61.5,
                              height: 30,
                              margin: EdgeInsets.only(left: 10, right: 10),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: AssetImage(
                                    ImageUtils.wrapAssets(
                                      'tab-$currentIndex${currentIndex == index ? '-active' : ''}.png',
                                    ),
                                  ),
                                ),
                              ),
                              alignment: Alignment.center,
                              child: Text(
                                tab.label,
                                style: TextStyle(
                                  height: 1,
                                  fontSize: 12,
                                  color: currentIndex == index
                                      ? Colors.white
                                      : currentTab.labelColor,
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  ),
                ),
                // TabBarView
                Expanded(
                  child: HideScrollShadow(
                    child: PageView(
                      controller: _pageController,
                      onPageChanged: _onPageChanged,
                      children: List.generate(
                        _tabList.length,
                        (index) => _tabList[index].tabbar,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 顶部 appbar
class IndexAppbar extends StatefulWidget {
  @override
  _IndexAppbarState createState() => _IndexAppbarState();
}

class _IndexAppbarState extends State<IndexAppbar> {
  Widget _badgeWrapBuild({
    required Widget child,
    String? text,
  }) {
    return Badge(
      badgeContent: text != null
          ? Text(
              text,
              style: TextStyle(
                color: Colors.white,
                fontSize: 10,
              ),
            )
          : SizedBox(),
      showBadge: text != null && text.isNotEmpty,
      animationType: BadgeAnimationType.fade,
      padding: EdgeInsets.all(5),
      position: BadgePosition(top: -5, end: -5),
      child: child,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: 50,
          padding: EdgeInsets.symmetric(
            horizontal: 10,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                children: [
                  // 任务
                  Image.asset(
                    ImageUtils.wrapAssets('task-icon.png'),
                    height: 35,
                    fit: BoxFit.fitHeight,
                  ),
                ],
              ),
              Row(
                children: [
                  _badgeWrapBuild(
                    // 搜索
                    child: Image.asset(
                      ImageUtils.wrapAssets('search-icon.png'),
                      height: 30,
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                  SizedBox(width: 10),
                  _badgeWrapBuild(
                    // 消息
                    child: Image.asset(
                      ImageUtils.wrapAssets('message-icon.png'),
                      height: 30,
                      fit: BoxFit.fitHeight,
                    ),
                    text: '4',
                  ),
                ],
              ),
            ],
          ),
        ),
        // 标题
        Positioned.fill(
          child: Center(
            child: Image.asset(
              ImageUtils.wrapAssets('title.png'),
              height: 32,
              fit: BoxFit.fitHeight,
            ),
          ),
        ),
      ],
    );
  }
}
